package com.heaven.jane.sourcegenerator.commons.security.user.controller;

import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.heaven.jane.sourcegenerator.commons.constant.ResultCode;
import com.heaven.jane.sourcegenerator.commons.exception.BusinessException;
import com.heaven.jane.sourcegenerator.commons.response.ResponseResult;
import com.heaven.jane.sourcegenerator.commons.security.user.domain.UserVo;
import com.heaven.jane.sourcegenerator.commons.security.user.service.UserService;

/**
 * 登录认证
 * @author heaven
 *
 */
@Controller
@RequestMapping("user")
public class UserController {
	
	@Autowired
	private UserService userService;
	
	/**
	 * 登录
	 * @param username
	 * @param password
	 * @return 账号信息
	 * @throws BusinessException 
	 */
	@ResponseBody
	@PostMapping(path = "login", consumes = "application/json")
	public ResponseResult login(@RequestBody UserVo user) throws BusinessException {
		UserVo loginUser = userService.findUser(user.getName(), user.getPassword());
		if(Optional.ofNullable(loginUser).isPresent()) {
			return ResponseResult.builder().data(loginUser).build();
		}else {
			throw BusinessException.build(ResultCode.AUTH_FAIL.getCode());
		}
	}
	

	@ResponseBody
	@GetMapping(path = "info")
	public ResponseResult info(String token) throws BusinessException {
		UserVo loginUser = userService.findUserByToken(token);
		if(Optional.ofNullable(loginUser).isPresent()) {
			return ResponseResult.builder().data(loginUser).build();
		}else {
			throw BusinessException.build(ResultCode.AUTH_FAIL.getCode());
		}
	}
	

}
